package com.example.autopia.view.Activities

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.Image
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.util.Patterns
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.example.autopia.R
import com.example.autopia.databinding.ActivityLoginBinding
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.User
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.PreferenceManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthException
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.bCreate.setOnClickListener {
            val intent = Intent(this, CreateAccActivity::class.java)
            startActivity(intent)
            finish()
        }

        binding.ibLogin.setOnClickListener {
            loginUser()
        }

        binding.btForgotPassword.setOnClickListener {
            showDialog()
        }
    }

    private fun loginUser() {
        val email = binding.etEmail.text.toString()
        val password = binding.etPassword.text.toString()

        val isValidated: Boolean = validateData(email, password)
        if (isValidated) {
            loginAccountInFirebase(email, password)
        }
    }

    private fun loginAccountInFirebase(email: String, password: String) {
        changeProgress(true)
        var firebaseAuth = Firebase.auth
        var userCars: ArrayList<Car>?
        var carsEmpty: Boolean = true
        firebaseAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this) { task ->
                changeProgress(false)
                if (task.isSuccessful) {
                    // login success, update UI with the login user's information
                    if (firebaseAuth.currentUser?.isEmailVerified == true) {
                        // добавление имя и почту пользователя в shared preference
                        val userPreference: PreferenceManager =
                            PreferenceManager(this@LoginActivity)
                        val userData: MutableLiveData<User> =
                            UsersRepository().getUserById(Firebase.auth.currentUser!!.uid)
                        userData.observe(this, Observer { user ->
                            userPreference.putString("userName", user.name)
                            userPreference.putString("userEmail", user.email)
                            userPreference.putString("userPhoto", user.photo)
                            userPreference.putString("userBalance", user.balance.toString())
                            userCars = user.carsList
                            carsEmpty = userCars.isNullOrEmpty()

                            if(carsEmpty) {
                                startActivity(Intent(this, CreateCarActivity::class.java))
                            } else {
                                startActivity(Intent(this, MainActivity::class.java))
                            }
                            finish()
                        })

                    } else {
                        FirebaseAuth.getInstance().signOut()
                        Toast.makeText(
                            this@LoginActivity,
                            "Email не подтвержден, пожалуйста, подтвердите email, пройдя по ссылке письма вашей почты",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    // If login fails, display a message to the user.
                    Log.d("frikadelka", task.exception.toString())
                    Log.d("frikadelka", task.exception?.localizedMessage.toString())
                    if (task.exception?.localizedMessage?.contains("INVALID_LOGIN_CREDENTIALS") == true) {
                        Toast.makeText(
                            this@LoginActivity,
                            "Введены неверные данные",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else if (task.exception?.localizedMessage?.contains("A network error") == true){
                        Toast.makeText(
                            this@LoginActivity,
                            "Нет соединения с Интернетом",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        Toast.makeText(
                            this@LoginActivity,
                            task.exception?.localizedMessage ?: "error",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                }
            }
    }

    private fun validateData(email: String, password: String): Boolean {
        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            binding.etEmail.error = "Некорректный формат почты"
            return false
        }
        if (password.length < 6) {
            binding.etPassword.error = "Пароль должен быть больше 5 символов"
            return false
        }
        return true
    }

    private fun changeProgress(inProgress: Boolean) {
        if (inProgress) {
            binding.loading.visibility = View.VISIBLE
            binding.cvLogin.visibility = View.GONE
        } else {
            binding.loading.visibility = View.GONE
            binding.cvLogin.visibility = View.VISIBLE
        }
    }

    private fun showDialog() {
        val dialog = Dialog(this@LoginActivity)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_forgot_password)

        val btClose = dialog.findViewById<ImageButton>(R.id.btClose)
        val etEmail = dialog.findViewById<EditText>(R.id.etEmail)
        val btContinue = dialog.findViewById<ImageButton>(R.id.btContinue)

        btContinue.setOnClickListener {
            Log.d("frikadelka", etEmail.text.toString())
            if (Patterns.EMAIL_ADDRESS.matcher(etEmail.text.toString()).matches()) {
                Firebase.auth.sendPasswordResetEmail(etEmail.text.toString())

                    .addOnSuccessListener {
                        dialog.dismiss()
                        Toast.makeText(
                            this@LoginActivity,
                            "Письмо для сброса пароля отправлено на почту",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                    .addOnFailureListener { exception ->
                        Toast.makeText(
                            this@LoginActivity,
                            exception.localizedMessage ?: "error",
                            Toast.LENGTH_LONG
                        ).show()
                    }
            } else {
                etEmail.error = "Неверная почта"
            }
        }
        btClose.setOnClickListener {
            dialog.dismiss()
        }

        dialog.show()
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window?.attributes!!.windowAnimations = R.style.DialogAnimation
        dialog.window?.setGravity(Gravity.BOTTOM)
    }
}